package com.neusiri.interceptor;

import com.neusiri.exception.BusinessException;
import com.neusiri.service.RedisService;
import io.netty.util.internal.StringUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * LoginInterceptor
 *
 * @author 丛有志
 * @date 2020/11/6 14:36
 * <p>
 * 版本        修改时间        作者        修改内容
 * V1.0        2020/11/6     丛有志        初始版本
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Resource
    private RedisService redisService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 无论访问的地址是不是正确的，都进行登录验证，登录成功后的访问再进行分发，404的访问自然会进入到错误控制器中
        String token = request.getHeader("token");
        if (StringUtil.isNullOrEmpty(token)) {
            throw new BusinessException(4002, "授权信息为空请重新登录");
        } else {
            if (!redisService.hasKey(token)) {
                // 跳到未登录页面
                request.getRequestDispatcher("/api/user/login").forward(request, response);
                throw new BusinessException(4002, "授权信息无效请重新登录");
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

}
